<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { dictContentFormSchema } from './dict.data'
import { addorUpdateDict } from '@/api/sys/dict';

defineOptions({ name: 'DictContentModal' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const dictId = ref()
const rowId = ref('')

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: dictContentFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  if (unref(isUpdate)) {
    dictId.value = data.record.dictId
    rowId.value = data.record.itemId
    setFieldsValue({
      ...data.record,
    })
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '添加字典组' : '编辑字典组'))

async function handleSubmit() {
  try {
    const values = await validate()
    console.log(values, dictId.value);
    setModalProps({ confirmLoading: true })
    let params: any = { ...values, dictName: values.dictNameCopy }
    if (unref(isUpdate)) {
      params = { ...params, dictId: dictId.value }
    }
    await addorUpdateDict(params)
    closeModal()
    emit('success')
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
